/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.kafka.common.network;


import org.apache.kafka.common.utils.Utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.security.Principal;

public class KafkaChannel { //负责字节操作的传输层,抽象的NetworkReceive和Send对象
    private final String id;
    private final TransportLayer transportLayer; //传输层负责字节操作的传输层
    private final Authenticator authenticator;
    private final int maxReceiveSize;
    private NetworkReceive receive;
    private Send send;
    // Track connection and mute state of channels to enable outstanding requests on channels to be
    // processed after the channel is disconnected.
    private boolean disconnected;
    private boolean muted;

    public KafkaChannel(String id, TransportLayer transportLayer, Authenticator authenticator, int maxReceiveSize) throws IOException {
        this.id = id;
        this.transportLayer = transportLayer;
        this.authenticator = authenticator;
        this.maxReceiveSize = maxReceiveSize;
        this.disconnected = false;
        this.muted = false;
    }

    public void close() throws IOException {
        this.disconnected = true;
        Utils.closeAll(transportLayer, authenticator);
    }

    /**
     * Returns the principal returned by `authenticator.principal()`.
     */
    public Principal principal() throws IOException {
        return authenticator.principal();
    }

    /**
     * Does handshake of transportLayer and authentication using configured authenticator
     */
    public void prepare() throws IOException {
        if (!transportLayer.ready())
            transportLayer.handshake();
        if (transportLayer.ready() && !authenticator.complete())
            authenticator.authenticate();
    }

    public void disconnect() {
        disconnected = true;
        transportLayer.disconnect();
    }


    public boolean finishConnect() throws IOException { //kafkaChannel要操作SocketChannel时,都交给传输层(transportLayer)去做
        return transportLayer.finishConnect();
    }

    public boolean isConnected() {
        return transportLayer.isConnected();
    }

    public String id() {
        return id;
    }

    public void mute() {
        if (!disconnected)
            transportLayer.removeInterestOps(SelectionKey.OP_READ);
        muted = true;
    }

    public void unmute() {
        if (!disconnected)
            transportLayer.addInterestOps(SelectionKey.OP_READ);
        muted = false;
    }

    /**
     * Returns true if this channel has been explicitly muted using {@link KafkaChannel#mute()}
     */
    public boolean isMute() {
        return muted;
    }

    public boolean ready() {
        return transportLayer.ready() && authenticator.complete();
    }

    public boolean hasSend() {
        return send != null;
    }

    /**
     * Returns the address to which this channel's socket is connected or `null` if the socket has never been connected.
     *
     * If the socket was connected prior to being closed, then this method will continue to return the
     * connected address after the socket is closed.
     */
    public InetAddress socketAddress() {
        return transportLayer.socketChannel().socket().getInetAddress();
    }

    public String socketDescription() {
        Socket socket = transportLayer.socketChannel().socket();
        if (socket.getInetAddress() == null)
            return socket.getLocalAddress().toString();
        return socket.getInetAddress().toString();
    }

    public void setSend(Send send) { //Selector调用send时,只是将请求设置到kafka通道中,必须确保没有正在进行中的其他请求
        if (this.send != null) //之前的请求还没有发送完毕,新的请求不能进来
            throw new IllegalStateException("Attempt to begin a send operation with prior send operation still in progress.");
        this.send = send; //将传入的Send参数设置为Kafka通道的成员变量(当没有请求或者上一个请求发送完毕,可以发送新请求)
        this.transportLayer.addInterestOps(SelectionKey.OP_WRITE); //注册写事件。选择器轮询时监听到写事件,调用KafkaChannel.write()方法
    }
    //选择器轮询时,检测到读事件时调用Kafka通道的read方法
    public NetworkReceive read() throws IOException { //kafka通道的read方法,最终会通过NetworkReceive.readFrom()调用传输层底层SocketChannel的read方法
        NetworkReceive result = null;

        if (receive == null) { //如果网络对象不存在,则新建一个
            receive = new NetworkReceive(maxReceiveSize, id); //id实际上会作为NetworkReceive的source
        }

        receive(receive);
        if (receive.complete()) {
            receive.payload().rewind();
            result = receive; //读取完成,设置返回结果
            receive = null; //读取全部完成,重置网络接收对象,下一次新的读取请求才可以继续正常进行
        }
        return result;
    }
    //选择器轮询时,检测到写事件时调用Kafka通道的write方法
    public Send write() throws IOException { //写事件处理方法,将setSend()时,保存到kafka通道的send发送到传输层的SocketChannel中
        Send result = null;
        if (send != null && send(send)) { //如果send方法返回值为false,表示请求还没有发送成功
            result = send;
            send = null; //请求发送完毕,设置send=null,才可以发送下一个请求
        }
        return result;
    }

    private long receive(NetworkReceive receive) throws IOException {
        return receive.readFrom(transportLayer); //使用已有的网络接收对象,从网络通道中读取数据,最终会调用SocketChannel。
    }

    private boolean send(Send send) throws IOException {
        send.writeTo(transportLayer);
        if (send.completed()) //Send请求全部写出去,取消写事件
            transportLayer.removeInterestOps(SelectionKey.OP_WRITE);

        return send.completed(); //Send没有写完全,会监听事件
    }

}
